package com.zhh.front.service;

import com.alibaba.fastjson.JSONObject;
import com.zhh.api.service.SmsService;
import com.zhh.common.contants.RedisKey;
import com.zhh.common.util.HttpClientUtils;
import com.zhh.front.config.AlySmsConfig;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service(value = "smsCodeRegisterImpl")
public class SmsCodeRegisterImpl implements SmsService {

    @Resource
    private AlySmsConfig smsConfig;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    //发送短信
    @Override
    public boolean sendSms(String phone) {
        boolean send = false;

        //随机数，验证码
        //String code = RandomStringUtils.randomNumeric(4);
        String code = "code:1234";

        //短信内容
        String content = smsConfig.getContent();

        //请求头
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", "APPCODE " + smsConfig.getAppkey());
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

        //请求体
        Map<String, Object> bodys = new HashMap<String, Object>();
        bodys.put("content", code);
        bodys.put("template_id", smsConfig.getContent());  //该模板为调试接口专用，短信下发有受限制，调试成功后请联系客服报备专属模板
        bodys.put("phone_number", phone);

        try {
            //使用HttpClient发送post请求给第三方
            String result = HttpClientUtils.doPost(smsConfig.getUrl(), headers, bodys);

            //解析响应结果
            if(StringUtils.isNotBlank(result)){
                JSONObject jsonObject = JSONObject.parseObject(result);

                if("OK".equals(jsonObject.getString("status"))){ //第三方接口调用成功
                    send = true;
                    //把手机号和验证码保存到redis
                    String key = RedisKey.KEY_SMS_CODE_REG + phone;
                    stringRedisTemplate.boundValueOps(key).set(code,3, TimeUnit.MINUTES);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return send;
    }

    //验证用户提交的验证码是否正确
    @Override
    public boolean checkSmsCode(String phone, String code) {
        String key = RedisKey.KEY_SMS_CODE_REG + phone;
        if(stringRedisTemplate.hasKey(key)){ //查看是否有值
            String querySmsCode = stringRedisTemplate.boundValueOps(key).get(); //把redis中的验证码取出来
            if(code.equals(querySmsCode)){ //比较验证码是否一致
                return true;
            }
        }
        return false;
    }
}
